<script lang="ts" setup>
import BaseButton from "@/components/BaseButton/index.vue";
import BaseUpDown from "@/components/BaseUpDown/index.vue";
import SelectLinksInput from "@/components/SelectLinksInput/index.vue";
import ConfigSentinel from "./components/ConfigSentinel/index.vue";
import useSearch from "@/hooks/useSearch";
import useData from "./hooks/useData";
import { ifaceLinks } from "@/api/modules/common";
import { ref } from "vue";
import { getIpRange, setIpRange } from "@/utils";
const { pageData } = useData();
import { getDataByPage, deleteData, exportData, importData } from "@/api/modules/dynamic-camouflage/sentinel-config";
import UpdateForm from "./components/UpdateForm/index.vue";

const { tableData, loadData, formData } = useSearch({
  defaultData: {},
  responseKey: {
    list: "data",
    total: "total"
  }
});
const links = ref([]);
const wanIfid = ref([]);
const lanIfid = ref([]);

async function getLinks() {
  const res = await ifaceLinks();
  console.log("==========", res);
  let arr = [];
  for (const link of res) {
    if (link.linkmode.includes("动态网络")) {
      let attr = link.ifid.split("-");
      arr.push({
        ifid: attr[0],
        linkid: link.linkid,
        name: `线路${link.linkid}-LAN`,
        label: `线路${link.linkid}`
      });
      lanIfid.value.push(attr[0]);
      // arr.push({
      //   ifid: attr[1],
      //   linkid: link.linkid,
      //   name: `线路${link.linkid}-WAN`,
      //   label:`线路${link.linkid}`
      // });
      // wanIfid.value.push(attr[1]);
    } else {
      arr.push({
        ...link,
        name: `线路${link.linkid}`,
        label: `线路${link.linkid}`
      });
    }
  }
  links.value = arr;
  if (arr?.length) {
    formData.ifid = arr[0].ifid;
  }
}

function updateSuccess(ifid) {
  if (ifid) {
    formData.ifid = ifid;
  }
  loadDataCb();
}

function selectLoad() {
  formData.pageNum = 1;
  formData.pageSize = 10;
  loadDataCb();
}

async function loadDataCb() {
  loadData({
    api: getDataByPage,
    sendData: {
      curpage: formData.pageNum - 1,
      perpage: formData.pageSize,
      ifid: formData.ifid
    }
  });
}

onMounted(async () => {
  await getLinks();
  loadDataCb();
});

/**删除*/
import useDelete from "@/hooks/useDelete";
import SelectIfaceInput from "@/components/SelectIfaceInput/index.vue";
import BaseCollapse from "@/components/BaseCollapse/index.vue";
import { onMounted } from "vue";
import moment from "moment/moment";
import { downloadTemplate } from "@/api/modules/resource/host-finger";
import { ElMessage } from "element-plus";

const { deleteHandler, idList } = useDelete();

async function deleteCb(row = {}) {
  console.log(row);
  await deleteHandler({
    api: deleteData,
    multiple: !Boolean(Object.keys(row).length > 0),
    sendData: {
      id: Boolean(Object.keys(row).length > 0) ? row.id : idList.value.join(","),
      ifid: formData.ifid
    },
    hideMessageBox: false
  });
  loadDataCb();
}

function selectCb(data) {
  console.log(data);
  idList.value = data.rowList.map(item => item.id);
}

async function templateOperate(type) {
  const urlDownload = function (url, name) {
    var a = document.createElement("a");
    // console.log(url)
    a.setAttribute("href", url);
    a.setAttribute("download", name);
    a.setAttribute("target", "_blank");
    const clickEvent = document.createEvent("MouseEvents");
    clickEvent.initEvent("click", true, true);
    a.dispatchEvent(clickEvent);
  };
  if (type === "export") {
    const res = await exportData({ ifid: formData.ifid });
    console.info(res);
    const url = URL.createObjectURL(res);
    urlDownload(url, `finger_${moment().format("YYYYMMDDHHmmss")}.csv`);
  }
  if (type === "download") {
    const res = await downloadTemplate();
    console.info(res);
    const url = URL.createObjectURL(res);
    urlDownload(url, `finger_template_${moment().format("YYYYMMDDHHmmss")}.csv`);
  }
  if (type === "import") {
    const tempInput = document.createElement("input");
    tempInput.type = "file";
    tempInput.accept = ".xls,.xlsx,.csv";
    tempInput.click();
    tempInput.addEventListener("change", async () => {
      const res = await importData({ file: tempInput.files[0], ifid: formData.ifid });
      if (res.success) {
        ElMessage.success("导入成功");
        loadDataCb();
      } else {
        ElMessage.warning(res.msg);
      }
    });
  }
  // this.waitOperator();
}
</script>

<template>
  <BaseUpDown>
    <template #up>
      <BaseCollapse title="虚拟节点">
        <template #header>
          <div class="h-box justify-end" style="width: 220px; float: right" @click.stop>
            <BaseButton @click="templateOperate('export')" class="mg-l-sm" type="export_icon_text" />
            <BaseButton :disabled="wanIfid.includes(formData.ifid)" @click="templateOperate('import')" type="import_icon_text" />
            <BaseButton @click="deleteCb" type="del_icon_text" />
            <UpdateForm
              :isLan="lanIfid.includes(formData.ifid)"
              :lanIfid="lanIfid"
              :ifid="formData.ifid"
              :links="links"
              @success="ifid => updateSuccess(ifid)"
            >
              <BaseButton :disabled="wanIfid.includes(formData.ifid)" type="add_icon_text" />
            </UpdateForm>
            <BaseButton class="mg-l-sm" @click="loadDataCb" type="refresh_icon_text" />
          </div>
        </template>
        <el-form label-position="right">
          <div class="h-box">
            <el-form-item label-width="0px" label="">
              <el-select placeholder="全部"  @change="selectLoad" style="width: 140px" v-model="formData.ifid">
                <el-option v-for="item in links" :key="item.ifid" :value="item.ifid" :label="item.label"></el-option>
              </el-select>
              <!--              <SelectLinksInput style="width: 140px" v-model="formData.ifid"></SelectLinksInput>-->
            </el-form-item>
          </div>
        </el-form>
      </BaseCollapse>
    </template>
    <he-table
      @handle-current-change="loadDataCb"
      :total="tableData.total"
      v-model:page-size="formData.pageSize"
      v-model:page-num="formData.pageNum"
      operate-width="180px"
      :operate-list="[]"
      :table-data="tableData.list"
      :column-data="pageData.columnData"
      :show-multiple="true"
      :show-summary="false"
      :show-operate="false"
      :show-multiple-column="false"
      :show-pagination="true"
      @select="selectCb"
    >
      <template #linenameDefault="{ data }">
        {{ links.find(item => item.ifid === formData.ifid)?.label }}
      </template>
      <template #iprangeDefault="{ data }">
        {{ setIpRange(data.row.iprange) }}
      </template>
      <template #typeDefault="{ data }">
        {{ data.row.type.includes("静态") ? "静态" : "动态" }}
      </template>
      <template #ipPercentDefault="{ data }">
        {{ data.row.iprate }}分钟
      </template>
      <template #portPercentDefault="{ data }">
        {{ data.row.portrate }}分钟
      </template>
      <template #operationDefault="{ data }">
        <UpdateForm
          isAutoHeight
          :isLan="lanIfid.includes(formData.ifid)"
          :links="links"
          :row-data="{
            ...data.row,
            ifid: formData.ifid,
            type: data.row.type.includes('静态') ? '1' : '2'
          }"
          :ifid="formData.ifid"
          :lanIfid="lanIfid"
          :title="`编辑节点`"
          @success="updateSuccess"
        >
          <base-button type="edit_text"></base-button>
        </UpdateForm>
        <ConfigSentinel
          :row-data="{
            ...data.row,
            ifid: formData.ifid,
            type: data.row.type.includes('静态') ? '1' : '2'
          }"
        >
          <base-button type="config_icon_text" class="mg-l-sm mg-r-sm"></base-button>
        </ConfigSentinel>
        <base-button @click="deleteCb(data.row)" type="del_text"></base-button>
      </template>
    </he-table>
  </BaseUpDown>
</template>
